package com.design.twords.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.design.twords.R;
import com.design.twords.adatper.WordsListAdapter;
import com.design.twords.config.ConstantValue;
import com.design.twords.database.OcrWordsList;
import com.design.twords.database.Translation_all;
import com.design.twords.database.Word_all;
import com.design.twords.entity.ItemWordList;
import com.design.twords.utils.MyApplication;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


/**
 * Create by Alen
 * Time:  23:44
 */
public class WordListActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "WordListActivity";

    private TextView wordlist_bookname;
    private RecyclerView words_list;
    private ImageView wordlist_back, deleteitem, additem, search;
    private LinearLayout bottom_btgroup;

    private WordsListAdapter wordsListAdapter;

    private static final int UPDATE_DATA = 3;


    private int currentItemNum = 0;
    private int addItemNumb = 10;

    private int floder_id;
    private String floder_name;
    private String typeById;
    private String sources;

    private List<ItemWordList> words = new ArrayList<>();
    //private List<ItemWordList> word_all = new ArrayList<>();
    private List<Word_all> word_alls = new ArrayList<>();


    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case UPDATE_DATA:
                    wordsListAdapter.notifyItemRangeChanged(currentItemNum,addItemNumb);
                    break;

            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wordlist);
        MyApplication.getInstance().addActivity(this);
        initView();
        initListener();

        sources = getIntent().getStringExtra("sources");
        floder_id = getIntent().getIntExtra("floder_id", 0);

        words_list.setLayoutManager(new LinearLayoutManager(this));
        if (floder_id != 0){
            if (sources.equals("ocr")){
                wordlist_bookname.setText("今日听写表");
                updateTodayWords();
                wordsListAdapter = new WordsListAdapter(this, words, R.layout.item_worddetail);
                words_list.setAdapter(wordsListAdapter);
            }
            else {
                floder_name = ConstantValue.bookNameById(floder_id);
                typeById = ConstantValue.getTypeById(floder_id);
                wordlist_bookname.setText(floder_name);

                updateData();
                wordsListAdapter = new WordsListAdapter(this, words, R.layout.item_worddetail);
                words_list.setAdapter(wordsListAdapter);

                words_list.addOnScrollListener(new RecyclerView.OnScrollListener() {
                    @Override
                    public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                        super.onScrolled(recyclerView, dx, dy);
                        LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                        //获取当前显示的最后一个单词的编号
                        int lastCompletelyVisibleItemPosition = manager.findLastCompletelyVisibleItemPosition();
                        //如果是初始加载的最后一个单词  就向单词表中添加数据
                        if (lastCompletelyVisibleItemPosition == manager.getItemCount() - 1){
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    //添加数据
                                    updateData();
                                }
                            }).start();
                        }
                    }
                });
            }

        }

        wordsListAdapter.setListener(myViewHolder -> bottom_btgroup.setVisibility(View.VISIBLE));


    }

    private String getTrans(long wordId, String wordBook) {
        List<Translation_all> transList = LitePal.where("wordId = ? and wordBook = ?", wordId+"", wordBook).find(Translation_all.class);
        if(transList.size() > 0){
            if (transList.get(0).getWordType() != null)
                return transList.get(0).getWordType()+": "+transList.get(0).getCHSMeaning();
            else
                return transList.get(0).getCHSMeaning();
        }
        return null;

    }

    private void updateTodayWords(){
        words.clear();
        List<OcrWordsList> all = LitePal.order("wordId asc").find(OcrWordsList.class);
        for (OcrWordsList owl :all){
            words.add(new ItemWordList(owl.getWordId(), owl.getWord(), owl.getWordBook(), getTrans(owl.getWordId(),owl.getWordBook()), "ocr"));
        }
    }

    private void updateData() {
        word_alls.clear();
        //获取数据 条目限制为 addItemNumb 起始偏移量为 currentItemNum
        word_alls = LitePal.select("wordId","word","wordBook").where("wordBook = ?", typeById).order("wordId asc")
                .limit(addItemNumb).offset(currentItemNum).find(Word_all.class);
        currentItemNum = addItemNumb + currentItemNum;
        for(Word_all word : word_alls){
            words.add(new ItemWordList(word.getWordId(), word.getWord(), word.getWordBook()
                    , getTrans(word.getWordId(), word.getWordBook()), "other"));
        }
        //回显一下 条目数
        Log.i(TAG, "word_alls.size"+word_alls.size());
        Log.i(TAG, "word_all.size"+words.size());
        //向主线程 发送消息 表示添加完成
        Message message = new Message();
        message.what = UPDATE_DATA;
        handler.sendMessage(message);

    }
    private void finishMsg(){
        Message message = new Message();
        message.what = UPDATE_DATA;
        handler.sendMessage(message);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()){
            case R.id.wordlist_delete:
                List<ItemWordList> check_words = wordsListAdapter.getCheck_words();
                for (ItemWordList item:check_words){
                    words.remove(item);
                    removeWord(item.getWordId(), item.getWordBook(), item.getFrom());
                }
                Toast.makeText(this, "删除成功",Toast.LENGTH_LONG).show();
                bottom_btgroup.setVisibility(View.GONE);
                wordsListAdapter.clearMap();
                wordsListAdapter.setSelectModel(false);
                wordsListAdapter.notifyDataSetChanged();
                break;
            case R.id.wordlist_add:
                List<ItemWordList> check_word = wordsListAdapter.getCheck_words();
                for (ItemWordList item:check_word){
                    addWord2Listen(item);
                }
                Toast.makeText(this, "添加成功",Toast.LENGTH_SHORT).show();
                bottom_btgroup.setVisibility(View.GONE);
                wordsListAdapter.clearMap();
                wordsListAdapter.setSelectModel(false);
                wordsListAdapter.notifyDataSetChanged();
                break;
            case R.id.wordlist_back:
                onBackPressed();
                break;
            case R.id.wordlist_search:
                intent.setClass(WordListActivity.this, SearchActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void removeWord(long wordId, String wordBook, String from){
        if (from.equals("ocr")){
            int i = LitePal.deleteAll(OcrWordsList.class, "wordId = ? and wordBook = ?", wordId + "", wordBook);
            Log.d(TAG,""+i);

        }
        LitePal.deleteAll(Word_all.class, "wordId = ? and wordBook = ?", wordId + "", wordBook);
    }

    private void addWord2Listen(ItemWordList item){
        List<OcrWordsList> ocrWordsLists = LitePal.where("word = ?", item.getWord()).find(OcrWordsList.class);
        if (!(ocrWordsLists.size() > 0)){
            OcrWordsList word = new OcrWordsList();
            word.setWordId(item.getWordId());
            word.setWord(item.getWord());
            word.setWordBook(item.getWordBook());
            word.save();
        }else {
            Toast.makeText(WordListActivity.this,"表中已有" + item.getWord(),Toast.LENGTH_SHORT).show();
        }
    }

    private void initView() {
        wordlist_bookname = findViewById(R.id.wordlist_bookname);
        words_list = findViewById(R.id.words_list);
        wordlist_back = findViewById(R.id.wordlist_back);

        bottom_btgroup = findViewById(R.id.wordlist_bottomview);
        deleteitem = findViewById(R.id.wordlist_delete);
        additem = findViewById(R.id.wordlist_add);
        search = findViewById(R.id.wordlist_search);

    }

    private void initListener(){
        wordlist_back.setOnClickListener(this);
        deleteitem.setOnClickListener(this);
        additem.setOnClickListener(this);
        search.setOnClickListener(this);

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        wordsListAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onStart() {
        super.onStart();


    }
}
